package com.luocj.looook.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.luocj.looook.R;
import com.luocj.looook.URL;
import com.luocj.looook.activity.WebViewActivity;
import com.luocj.looook.adapter.BaseRecyclerAdapter;
import com.luocj.looook.adapter.SmartViewHolder;
import com.luocj.looook.base.BaseFragment;
import com.luocj.looook.event.TestEvent;
import com.luocj.looook.model.MeiNvModel;
import com.luocj.looook.utils.Constant;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luocj515 on 2017/11/24.
 * 项目名称：LooooK
 * 类描述：
 * 创建人：hasee
 * 创建时间：2017/11/24 17:33
 * 修改备注：
 */

public class MEINVFragment extends BaseFragment {
    private static final String TAG = MEINVFragment.class.getSimpleName();

    private SmartRefreshLayout smartFreshLayout;
    private RecyclerView recyclerView;

    private List<MeiNvModel.NewslistBean> meinvModel = new ArrayList<>();
    private BaseRecyclerAdapter<MeiNvModel.NewslistBean> meinvAdapter;
    private boolean isFirstIn = true;

    private int PAGE_SIZE = 10;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mContentView != null) {
            return mContentView;
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    protected int getLayoutId() {

        return R.layout.fragment_meinv;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        smartFreshLayout = mContentView.findViewById(R.id.smartrefreshlayout_meinv);
        recyclerView = mContentView.findViewById(R.id.recyclerview_meinv);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContentView.getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                Log.i(TAG, "onScrollStateChanged: " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                Log.i(TAG, "onScrolled: " + "dx:" + dx + "------>" + "dy:" + dy);
            }
        });

        meinvAdapter = new BaseRecyclerAdapter<MeiNvModel.NewslistBean>(meinvModel, R.layout.item_meinv, null) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, final MeiNvModel.NewslistBean model, final int position) {
                ImageView meinvPic = holder.itemView.findViewById(R.id.iv_meinv_pic);
                Glide.with(getActivity())
                        .load(model.getPicUrl())
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher_round)
                        .centerCrop()
                        .into(meinvPic);

//                Log.i(TAG, "onBindViewHolder: " + model.getUrl());

                meinvPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra(WebViewActivity.DATA_URL, model.getUrl());
                        startActivity(intent);
                    }
                });

                meinvPic.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
//                        Log.i(TAG, "onLongClick: " + position);
                        EventBus.getDefault().post(new TestEvent(position, model.getDescription()));
                        return true;
                    }
                });
            }
        };

        recyclerView.setAdapter(meinvAdapter);
        if (isFirstIn) {
            isFirstIn = false;
            smartFreshLayout.autoRefresh();
        }

        smartFreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshData(true);
                    }
                }, 2000);
            }
        });

        smartFreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshData(false);
                    }
                }, 2000);
            }
        });

    }

    private void refreshData(final boolean isFresh) {

        if (isFresh) {
            PAGE_SIZE = 10;
        } else {
            PAGE_SIZE = PAGE_SIZE + 10;
        }

        OkGo.<String>get(URL.BASE_URL_MEINV)
                .params("key", "861a794733dd2b057e415d822bef9586")
                .params("num", PAGE_SIZE)
                .tag(TAG)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        Log.i(TAG, "onSuccess: " + response.body().toString());
                        MeiNvModel meiNvModel = JSONObject.parseObject(response.body().toString(), MeiNvModel.class);
                        for (int i = 0; i < meinvModel.size(); i++) {
                            Log.i(TAG, "onSuccess: " + meinvModel.get(i).getUrl());
                        }
                        if (isFresh) {
                            meinvAdapter.refresh(meiNvModel.getNewslist());
                            smartFreshLayout.finishRefresh();
                            smartFreshLayout.setLoadmoreFinished(false);
                        } else {
                            meinvAdapter.loadmore(meiNvModel.getNewslist().subList(meinvAdapter.getItemCount(), meiNvModel.getNewslist().size()));
                            smartFreshLayout.finishLoadmore();
                            if (meinvAdapter.getItemCount() >= Constant.MAX_SIZE) {
                                smartFreshLayout.setLoadmoreFinished(true);
                            }
                        }

//                        Log.i(TAG, "onSuccess: " + "item count" + meinvAdapter.getItemCount());

                    }

                    @Override
                    public void onError(Response<String> response) {

//                        Log.i(TAG, "onError: " + response.toString());
                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
//        Log.i(TAG, "onPause: ");
    }

    @Override
    public void onStop() {
        super.onStop();
//        Log.i(TAG, "onStop: ");
    }

    @Override
    public void onDestroy() {
        isFirstIn = true;
        super.onDestroy();
//        Log.i(TAG, "onDestroy: ");
    }

}
